var
    util = require('util'),
    redis = require('./../redis.js'),
    config = require("../../../../config.js"),
    async = require("async"),
    mysql = require("mysql"),
    pool = mysql.createPool(config.mysql),
    httpUtil = require("../../../../lib/httpUtil.js"),
    crypto = require("crypto");


var KEY = {
    USER: 'user:id:%s',
    USER_USERNAME: 'user:username:%s'
};


module.exports.KEY = KEY;

module.exports.getId = function (user) {
    return user.id;
};

var fetchById = function (id, cb) {
    async.waterfall([function (cb) {
            pool.getConnection(cb);
        }, function (result, cb) {
            var connection = result;
            var sql = "select * from USER_ACCOUNT where id='" + id + "'";
            connection.query(sql, function (err, data) {
                if (err) {
                    cb(err);
                } else {
                    cb(null, data[0]);
                }
                connection.release();
            });
        }
        ],
        function (err, result) {
            if (err) {
                cb(err)
            } else {
                cb(null, result);
            }
        }
    )
};

module.exports.fetchById = fetchById;

module.exports.fetchByUsername = function (username, cb) {
    async.waterfall([function (cb) {
            pool.getConnection(cb);
        }, function (result, cb) {
            var connection = result;
            var sql = "select * from USER_ACCOUNT where mobile='" + username + "'";
            connection.query(sql, function (err, data) {
                if (err) {
                    cb(err);
                } else {
                    cb(null, data[0]);
                }
                connection.release();
            });
        }
        ],
        function (err, result) {
            if (err) {
                cb(err)
            } else {
                cb(null, result);
            }
        }
    )
};

module.exports.login = function (username, password, clientId, cb) {
    var params = {
        "mobile": username,
        "password": password,
        "group": config.user.group,
        "clientId": clientId,
        "clientType": config.user.clientType
    }
    httpUtil.POST(config.user.host, config.user.url, params, cb);
};

module.exports.checkPassword = function (user, password) {
    if (!user) {
        return false;
    }
    var sha1 = crypto.createHash("sha1");
    sha1.update(password);
    return user.password === sha1.digest("hex");
};

module.exports.fetchFromRequest = function (req) {
    return req.session.user;
};